const webdriver = require('selenium-webdriver'), By = webdriver.By
const {URL} = require('url')
const fs = require('fs')
const tough = require('tough-cookie');

const config = require('./config.js')
const FileCookieStore = require('./filestore.js')

const driver = new webdriver.Builder().forBrowser('phantomjs').build()

const manage = driver.manage()

const url = new URL(process.argv[2])

async function addCookie(cookie_file, domain) {
    if (fs.existsSync(cookie_file)) {
        await new Promise((resolve) => {
            const fileCookieStore = new FileCookieStore(config.cookie_file)
            const promises = []
            fileCookieStore.findCookies(domain, null, (err, cookies) =>{
                cookies.forEach(cookie => {
                    console.log({
                        name: cookie.key,
                        value: cookie.value,
                        path: cookie.path,
                        domain: cookie.domain,
                        httpOnly: cookie.httpOnly,
                        expiry: cookie.TTL(),
                        secure: cookie.secure
                    })

                    promises.push(manage.addCookie({
                        name: cookie.key,
                        value: cookie.value,
                        path: cookie.path,
                        domain: cookie.domain,
                        httpOnly: cookie.httpOnly,
                        expiry: cookie.TTL(),
                        secure: cookie.secure
                    }))
                })
            })
            resolve(Promise.all(promises))
        })
    }
}


addCookie(config.cookie_file, url.hostname).then(() => {
    driver.get(url.href)
    driver.actions().dragAndDrop(By.id('nc_1_n1z'), {x: 258})
    driver.wait(function() {
        return driver.findElement(By.id('fm-noc-ua')).then((element) => {
            return element.value !== ''
        })
    }, 3000)
    driver.findElement(By.id('submitBtn')).click()
    driver.quit()
})

